import React from 'react';
import { bindActionCreators } from 'redux';
import classNames from 'classnames';
import { connect } from 'react-redux';
import { Link } from 'react-router';

import * as Util from '../common/Util';
import * as ProductActions from '../actions/ProductActions';
import * as UserActions from '../actions/UserActions';

import {
  Row,
  Col,
  Button,
  Panel,
  TabbedArea,
  TabPane
} from 'react-bootstrap';

import Pager from '../components/Pager';
import DialogCommon from '../components/DialogCommon';
import DialogAlert from '../components/dialog/DialogAlert';
import Notify from '../common/Notification';
import ProductBar from '../components/ProductBar';
import Container from '../components/Container';
import { pageSize } from '../config/Common';
import { product as ProductConfig, domain } from '../config/Common';

class ProductDetailApp extends React.Component {

  constructor () {
    super();  

    this.historyPageIndex  = 1;

    this.praiseHistoryStatus = 0;

    this.state = {
       product : {},
       dialogVisiable : false,
       dialogTitle : "",
       dialogContent : <div>系统提示</div>,
       dialogButton : null,
       selectedTabKey : 1
    }; 
  }

  static propTypes = {
    product: React.PropTypes.array.isRequired,
    dispatch: React.PropTypes.func.isRequired
  }

  static contextTypes = {
    router: React.PropTypes.object.isRequired
  }

  fetchHistoryData(){
    let { product } = this.state;
    let dataParam = {
        start : this.historyPageIndex, 
        limit : pageSize,
        pid : product.gsid
    };
    this.props.productAction.fetchHistory(dataParam);
  }

  componentDidMount(){
    let { product, user } = this.props;
    let pid = this.props.location.query.id;
    let productInfo = null;
    if(product && product.results && product.results.length){
      for(let i =0 ,len = product.results.length; i < len; i++){
        let productItem = product.results[i];
        if (productItem.gsid === pid) {
          productInfo = productItem;
          break;
        }
      }
    }

    this.setState({
      product: productInfo
    });

    if(user && user.isauth === "1"){
      let timer = setInterval(function(){
        if(this.state.product!==null){
          clearInterval(timer);
          this.fetchHistoryAndHolding(this.historyPageIndex);
        }
      }.bind(this), 100);
    }
  }

  getRenderStyle(val){
    let isHappy = (parseFloat(val) >= 0 ? true : false);
    let happyClass = {
        "text-success": !isHappy,
        "text-danger": isHappy
    };
    let currentClass = classNames( happyClass );
    return currentClass;
  }

  getHistoryPageDisable(){

    let { product } = this.state;

    let pageTotalCount = (this.historyPageIndex) * pageSize;
    let historyPageDisable = false;
    if(product.history && product.history.length >= pageTotalCount){
      historyPageDisable = true;
    }
    return historyPageDisable;
  }

  onHistoryPageClick(){
    let pIndex = this.historyPageIndex;
    this.historyPageIndex = pIndex + 1;
    this.fetchHistoryData();
  }

  handleProductLike(){
      let { product } = this.state;
      this.props.productAction.PraiseProduct(product.gsid);
  }

  handleHistoryLike(history, event){
    if(this.praiseHistoryStatus === 0){
      this.praiseHistoryStatus = 1;
      
      let { product } = this.state;

      let dataParam = {
        pid : product.gsid,
        mid : history.mid
      };
      this.props.productAction.praiseHistory(dataParam);
    }
  }

  componentDidUpdate(){
    let { product } = this.props;

    this.praiseHistoryStatus = 0;

    if (product) {
      let { product_sign_status = 0, product_unsign_status = 0, message = "" } = product;

      product.product_sign_status = 0;
      product.product_unsign_status = 0;

      if (product_sign_status === -1 || product_unsign_status === -1) {
          let dialogHeader = `系统提示`;
          let dialogContent  = <DialogAlert message={message}/>
          this.setState({
            dialogContent : dialogContent,
            dialogVisiable : true,
            dialogTitle : dialogHeader,
            dialogButton : [{
               text : "确定",
               style : "default"
            }]
          });
      }else if(product_sign_status === 1 || product_unsign_status === 1){
          this.fetchHistoryAndHolding(1);
          //this.props.userAction.fetchUser();
      }
    }
  }

  renderProductInfo(){
    let { product } = this.state;
    return (
        <Panel className="product-item message-item margin-top-none border-radius-no">
          <div className="product-avatar">
              <img src={`${domain}${product.avatar}`} className="img-circle" />
          </div>
          <div className="product-detail full">
              <h4 className="text-info title">
                {product.name}
              </h4>
              <p className="text-muted item">
                <label>{product.realname}：</label>
                <span>{product.certnum}</span>
              </p>
          </div>
          <div className="devider"></div>
          <div className="product-descr text-primary">
              策略介绍：{product.descript||"暂无"}
          </div> 
        </Panel>
    )
  }

  renderBaseInfo(){
      let { product } = this.state;
      return (
        <div>
           <Panel className="text-center border-radius-no">
            <Row>
              <Col xs={4}>
                  <p className="text-primary">
                    盈亏比
                  </p>
                  <p className="text-primary">
                    <span className="text-danger">{product.profitnum||"--"}</span>盈
                    <span>{product.lossnum||"--"}</span>亏
                  </p>
              </Col>
              <Col xs={4}>
                  <p className="text-primary">
                    胜率
                  </p>
                  <p className="text-danger">
                    {parseFloat(product.successrate).toFixed(2)}%
                  </p>
              </Col>
              <Col xs={4}>
                  <p className="text-primary">
                    关注数
                  </p>
                  <p className="text-primary">
                    {product.viewcount||"--"}
                  </p>
              </Col>
            </Row>
            <div className="devider-full"></div>
            <Row>
              <Col xs={3}>
                  <p className="text-primary">
                    本周累计
                  </p>
                  <p className="text-danger">
                    {
                      product.weekrate === ""?
                      `0.00%`
                      :
                      `${parseFloat(product.weekprofit).toFixed(2)}%`
                    }
                  </p>
              </Col>
              <Col xs={3}>
                  <p className="text-primary">
                    本月累计
                  </p>
                  <p className="text-danger">
                    {
                      product.monthrate === ""?
                      `0.00%`
                      :
                      `${parseFloat(product.monthprofit).toFixed(2)}%`
                    }
                  </p>
              </Col>
              <Col xs={3}>
                  <p className="text-primary">
                    本季累计
                  </p>
                  <p className="text-danger">
                    {
                      product.seasonrate === ""?
                      `0.00%`
                      :
                      `${parseFloat(product.seasonprofit).toFixed(2)}%`
                    }
                  </p>
              </Col>
              <Col xs={3}>
                  <p className="text-primary">
                    本年累计
                  </p>
                  <p className="text-danger">
                    {
                      product.yearrate === ""?
                      `0.00%`
                      :
                      `${parseFloat(product.yearprofit).toFixed(2)}%`
                    }
                  </p>
              </Col>
            </Row>
          </Panel>
          
          <div className="padding text-center">
              <Button bsSize="large" bsStyle="danger" className="btn-circle" onClick={ this.handleProductLike.bind(this) }>
                <i className="iconfont icon-praise"></i>
                <span>
                  {
                    parseInt(product.praisenum||"0")>0?
                    `${product.praisenum}`
                    :
                    `0`
                  }
                </span>
              </Button>
          </div>
        </div>                       
      )
  }

  renderHoldingItem(holding){
    return (
      <Row className="product-data-row">
        <Col xs={3}>
            <p>
                {holding.stockname}
            </p>
            <p>
                {holding.stockcode}
            </p>
        </Col>
        <Col xs={3}>
            <p>
                现价&nbsp;{parseFloat(holding.nowprice).toFixed(2)}
            </p>
            <p>
                成本&nbsp;{parseFloat(holding.costprice).toFixed(2)}
            </p>
        </Col>
        <Col xs={3}>
            <p className="product-data-single">
                仓位&nbsp;100%
            </p>
        </Col>
        <Col xs={3}>
            <p className="product-data-single">
              盈亏&nbsp;<span className={ this.getRenderStyle(holding.profit) }>{ parseFloat(holding.profit).toFixed(2) }%</span>
            </p>
        </Col>
      </Row>
    );
    
  }

  renderHistoryItem(history){
      return(

        history.stockname?
        <div>
          <Row className="product-data-row">
            <Col xs={3}>
                <p>
                    {history.stockname}
                </p>
                <p>
                    {history.stockcode}
                </p>
            </Col>
            <Col xs={3}>
                <p>
                    操作&nbsp;{history.operate==="2"?`卖出`:`买入`}
                </p>
                <p>
                    价格&nbsp;{parseFloat(history.costprice).toFixed(2)}
                </p>
            </Col>
            <Col xs={4}>
                <p>
                  盈亏&nbsp;
                  { 
                    history.operate === "2"?
                    <span className={this.getRenderStyle(history.profit) }>{ parseFloat(history.profit).toFixed(2) }%</span>
                    : "—"  
                  }
                </p>
                <p>
                  时间&nbsp;{Util.DateFormater(history.jydatetime, "MM-dd")}
                </p>
            </Col>
            <Col xs={2}>
                <p className="text-danger product-data-single product-data-like" onClick={this.handleHistoryLike.bind(this, history)}>
                    <i className="iconfont icon-praise"></i>
                    &nbsp;{
                      parseInt(history.praisenum||"0")>0?
                      `${history.praisenum}`
                      :
                      `0`
                    }
                </p>
            </Col>
          </Row>
          <div className="devider-full"></div>
        </div>
        :
        null
      );
  }

  renderHistory(){

      let { product } = this.state;

      let { user } = this.props;

      let historyPageDisable = null;
      if( user && user.isauth === "1"){
        historyPageDisable = this.getHistoryPageDisable();
      }

      return (

          user && user.isauth==="1"?
          <div className="box-shadow">
            <Panel header="当前持仓" className="panel-thin">
                {
                    product.holding && product.holding.length>0 ?
                    product.holding.slice(0,10).map((holding, i) =>{
                        return (
                          this.renderHoldingItem(holding)
                        );
                    }) 
                    :
                    <div className="text-center text-danger">
                      当前暂无持仓
                    </div>
                } 
            </Panel>
            <Panel header="近期操作" className="panel-thin">
              {
                  product.history && product.history.length > 0?
                  product.history.slice(0, pageSize * this.historyPageIndex).map((history, i) =>{
                      return (
                        this.renderHistoryItem(history)
                      );
                  })
                  :
                  <div className="text-center text-danger">
                    暂无操作历史
                  </div>
              }

              {
                  historyPageDisable || (product.history && product.history.length > 0)?
                  <Pager 
                    enabled = { historyPageDisable }
                    status = { this.props.product.history_status }
                    onPageClick = {this.onHistoryPageClick.bind(this)}>
                    点击加载更多
                  </Pager>
                  :null
              }
            </Panel>
          </div>
          :
          <div className="box-shadow">
             <Panel>
              <div className="padding-lg text-center">
                <small className="text-muted">绑定证券账户，可查看历史操作</small>
                <div className="blank20">
                </div>
                <Link to="/Bind">
                  <Button bsStyle="primary" block>
                      立即绑定
                 </Button>
                </Link>
              </div>
             </Panel>
          </div>
      );
  }

  handleDialogHide(){
    this.setState({
       dialogVisiable : false
    });
  }

  fetchHistoryAndHolding(pIndex){
    let { product } = this.state;
    let { productAction } = this.props;
    let dataParam = {
        pid : this.state.product.gsid
    };

    //获取策略持仓列表
    productAction.fetchHolding(dataParam);
    dataParam.start = pIndex;
    dataParam.limit = pageSize;
    //获取策略操作历史
    if (pIndex <= 1) {
      product.history = [];
    }
    this.props.productAction.fetchHistory(dataParam);
  }


  handleTabSelect(index){
    this.setState({
      selectedTabKey : index
    });
  }

  render() {

    let { user, history, productAction } = this.props;

    return (
          <Container 
              isGoBack={true} 
              isHeader={true}
              isScroll={false} 
              isFooter={false} 
              headerTitle={"策略详情"}>
              
               <div className="product-container padding-none">

                  { this.renderProductInfo() }

                  {
                    /*
                      <TabbedArea activeKey={this.state.selectedTabKey} onSelect={ this.handleTabSelect.bind(this) }>  
                    */
                  }
                  <TabbedArea defaultActiveKey={1}>
                    <TabPane eventKey={1} tab="基本信息">
                        { this.renderBaseInfo() }
                    </TabPane>

                    <TabPane eventKey={2} tab="历史操作">
                        { this.renderHistory() }
                    </TabPane>
                  </TabbedArea>

                  <div className="blank50"></div>
                  <ProductBar product={ this.state.product } history={ history } user={ user } productAction={ productAction }/>
               </div>
               <DialogCommon 
                  title={ this.state.dialogTitle } 
                  content={ this.state.dialogContent } 
                  buttons = { this.state.dialogButton }
                  visiable={ this.state.dialogVisiable } 
                  onHide = { this.handleDialogHide.bind(this) }/>
          </Container>
    );
  }
}

export default connect(state => ({
    product: state.product,
    user : state.user
}), dispatch => ({
    productAction: bindActionCreators(ProductActions, dispatch),
    userAction : bindActionCreators(UserActions, dispatch)
}))(ProductDetailApp);
